package bar.dark.lee.cashdrawing;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.Animation.AnimationListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.CompoundButton.OnCheckedChangeListener;
import bar.dark.lee.BDConstents;
import bar.dark.lee.R;
import bar.dark.lee.SuperActivity;
import bar.dark.lee.common.BDUtil;
import bar.dark.lee.common.CalendarPickerDialog;
import bar.dark.lee.common.DBSQLite;
import bar.dark.lee.common.RadioDialogActivity;
import bar.dark.lee.common.DBSQLite.ParseSelectData;
import bar.dark.lee.common.EditTextInputFilter;
import bar.dark.lee.insert.BalanceQuery;
import bar.dark.lee.insert.InsertInActivity;
import bar.dark.lee.insert.InsertOutActivity;
import bar.dark.lee.select.SelectActivity;
import bar.dark.lee.setting.TipInfoActivity;
import bar.dark.lee.setting.TipsActivity;

public class CashDrawingActivity extends SuperActivity
{
	public static final int REQUEST_BANK = 0;
	public static final int REQUEST_CHECK = 1;
	public static final int REQUEST_CREDIT = 2;
	public static final int REQUEST_CATEGORY = 4;
	
	private DBSQLite sql;
	
	private RadioButton checkRadioButton;
	private RadioButton creditRadioButton;
	private RadioButton bankRadioButton;
	
	private TextView realMoney;
	
	private TextView balanceText;
	private TextView balanceMoney;
	private View checkView;
	private View creditView;
	private View bankView;
	private TextView checkTextView;
	private TextView creditTextView;
	private TextView bankTextView;
	
	private View dateView;
	private TextView dateTextView;
	
	private View categoryView;
	private TextView categoryTextView;
	
	private EditText money;
	private EditText charge;
	
	private View memoView;
	private EditText memo;
	private Button insertButton;
	
	private ArrayList<String> bankList;
	private ArrayList<String> checkList;
	private ArrayList<String> creditList;
	
	private ArrayList<String> categoryList;
	
	// 날짜
	private int toYear;
	private int toMonth;
	private int toDay;
	
	private int linkId = -1;
	private int inoutLinkId = -1;
	private int linkType = -1;
	
	private int firstBankRadio = 0;
	
	private BigDecimal chargeMoney = BigDecimal.ZERO;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		sql = DBSQLite.getInstance(this);
		
		setContentView(R.layout.cashdrawing_activity);
		
		setGoneTitle();
		
		initFindView();
		initClickListener();
		initDataSetting();

		SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
    	int flag = pref.getInt(BDConstents.INOUT_MANAGER_SELECT_FLAG, 0);
    	
    	if (flag == 1)
    	{
    		setBankRadioClick();
    	}
    	else if (flag == 2)
    	{
    		setCreditRadioClick();
    	}
    	else
    	{
    		setCheckRadioClick();
    	}
	}
	
	@Override
	protected void onDestroy()
	{
		super.onDestroy();
		
		SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
		SharedPreferences.Editor editor = pref.edit();
		
		int flag = 0;
		
		if (bankRadioButton.isChecked())
		{
			flag = 1;
		}
		else if (creditRadioButton.isChecked())
		{
			flag = 2;
		}
		else
		{
			flag = 0;
		}
		
		editor.putInt(BDConstents.INOUT_MANAGER_SELECT_FLAG, flag);
		
		editor.commit();
	}
	
	private void initFindView()
	{
		checkRadioButton = (RadioButton) findViewById(R.id.cashdrawingCheckRadio);
		creditRadioButton = (RadioButton) findViewById(R.id.cashdrawingCreditRadio);
		bankRadioButton = (RadioButton) findViewById(R.id.cashdrawingBankRadio);
		
		realMoney = (TextView) findViewById(R.id.cashdrawingRealMoney);
		
		balanceText = (TextView) findViewById(R.id.cashdrawingBalanceText);
		balanceMoney = (TextView) findViewById(R.id.cashdrawingBalance);
		checkView = findViewById(R.id.cashdrawingCheckView);
		creditView = findViewById(R.id.cashdrawingCreditView);
		bankView = findViewById(R.id.cashdrawingBankView);
		
		checkTextView = (TextView) findViewById(R.id.cashdrawingCheckKind);
		creditTextView = (TextView) findViewById(R.id.cashdrawingCreditKind);
		bankTextView = (TextView) findViewById(R.id.cashdrawingBankKind);
		
		dateView = findViewById(R.id.cashdrawingDate);
		dateTextView = (TextView) findViewById(R.id.cashdrawingDateTextView);
		
		categoryView = findViewById(R.id.cashdrawingCategory);
		categoryTextView = (TextView) findViewById(R.id.cashdrawingCategoryTextView);
		
		money = (EditText) findViewById(R.id.cashdrawingMoney);
		EditTextInputFilter.filteringMoneyEditText(money);
		charge = (EditText) findViewById(R.id.cashdrawingCharge);
		EditTextInputFilter.filteringMoneyEditText(charge);
		
		memoView = findViewById(R.id.cashdrawingMemoView);
		memo = (EditText) findViewById(R.id.cashdrawingMemo);
		insertButton = (Button) findViewById(R.id.cashdrawingInsertButton);
	}
	
	private void initDataSetting()
	{
		Calendar cal = Calendar.getInstance();
		toYear = cal.get(Calendar.YEAR);
		toMonth = cal.get(Calendar.MONTH);
		toDay = cal.get(Calendar.DAY_OF_MONTH);
		
		dateTextView.setText(BDUtil.getDate(toYear, toMonth+1, toDay));
		
		sql.selectMapTile(superContext, "SELECT * FROM real_money;", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int moneyIdx = c.getColumnIndex("money");
				
				c.moveToFirst();
				
				BigDecimal money = BigDecimal.ZERO;
				
				for (int i = 0; i < c.getCount(); i++)
				{
					money = money.add(new BigDecimal(c.getString(moneyIdx)));
					c.moveToNext();
				}
				
				realMoney.setText(BDUtil.getWon(money.toString()) + shape);
			}
		});
		
		sql.selectMapTile(this, "SELECT kind FROM category_move_list ORDER BY count DESC", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				categoryList = new ArrayList<String>();
				
				int nameIndex = c.getColumnIndex("kind");
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					String kind = c.getString(nameIndex);
					categoryList.add(kind);
					c.moveToNext();
				}
				
				if (categoryList.size() < 1)
				{
					String memo = "없음";
					categoryList.add(memo);
					categoryView.setClickable(false);
				}
				else
				{
					categoryView.setClickable(true);
				}
				
				categoryTextView.setText(categoryList.get(0).toString());
			}
		});
		
		sql.selectMapTile(this, "SELECT name FROM ( " +
								"SELECT b.name name " +
								"FROM check_card b, checkcard_detail d " +
								"WHERE b.id = d.linkid and d.count > 0 ORDER BY d.count) " +
								"UNION ALL " +
								"SELECT name FROM ( " +
								"SELECT b.name name " +
								"FROM check_card b, checkcard_detail d " +
								"WHERE b.id = d.linkid and d.count < 1 ORDER BY d.count);", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				checkList = new ArrayList<String>();
				
				int nameIndex = c.getColumnIndex("name");
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					String kind = c.getString(nameIndex);
					checkList.add(kind);
					c.moveToNext();
				}
				
				if (checkList.size() < 1)
				{
					String memo = "없음";
					checkList.add(memo);
					checkView.setClickable(false);
					checkView.setTag(false);
				}
				else
				{
					checkView.setClickable(true);
					checkView.setTag(true);
				}
				
				checkTextView.setText(checkList.get(0).toString());
			}
		});
		
		sql.selectMapTile(this, "SELECT name FROM ( " +
								"SELECT b.name name " +
								"FROM credit_card b, creditcard_detail d " +
								"WHERE b.id = d.linkid and d.count > 0 ORDER BY d.count) " +
								"UNION ALL " +
								"SELECT name FROM ( " +
								"SELECT b.name name " +
								"FROM credit_card b, creditcard_detail d " +
								"WHERE b.id = d.linkid and d.count < 1 ORDER BY d.count);", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				creditList = new ArrayList<String>();
				
				int nameIndex = c.getColumnIndex("name");
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					String kind = c.getString(nameIndex);
					creditList.add(kind);
					c.moveToNext();
				}
				
				if (creditList.size() < 1)
				{
					String memo = "없음";
					creditList.add(memo);
					creditView.setClickable(false);
					creditView.setTag(false);
				}
				else
				{
					creditView.setClickable(true);
					creditView.setTag(true);
				}
				
				creditTextView.setText(creditList.get(0).toString());
			}
		});
		
		sql.selectMapTile(this, "SELECT name FROM ( " +
								"SELECT b.name name FROM bankbook b, bankbook_detail d " +
								"WHERE b.id = d.linkid and d.count > 0 ORDER BY d.count) " +
								"UNION ALL " +
								"SELECT name FROM ( " +
								"SELECT b.name name FROM bankbook b, bankbook_detail d " +
								"WHERE b.id = d.linkid and d.count < 1 ORDER BY d.count);", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				bankList = new ArrayList<String>();
				
				int nameIndex = c.getColumnIndex("name");
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					String kind = c.getString(nameIndex);
					bankList.add(kind);
					c.moveToNext();
				}
				
				if (bankList.size() < 1)
				{
					String memo = "없음";
					bankList.add(memo);
					bankView.setClickable(false);
					bankView.setTag(false);
				}
				else
				{
					bankView.setClickable(true);
					bankView.setTag(true);
				}
				
				bankTextView.setText(bankList.get(0).toString());
			}
		});
		
		setBalanceCheckMoney();
	}
	
	private void setCheckRadioClick()
	{
		checkRadioButton.setChecked(true);
		bankRadioButton.setChecked(false);
		creditRadioButton.setChecked(false);
		
		if (creditView.getVisibility() == View.VISIBLE)
		{
			creditView.setVisibility(View.GONE);
		} 
		else if (bankView.getVisibility() == View.VISIBLE)
		{
			bankView.setVisibility(View.GONE);
		}
		
		firstBankRadio = 1;
		checkView.setVisibility(View.VISIBLE);
		setBalanceCheckMoney();
	}
	
	private void setCreditRadioClick()
	{
		creditRadioButton.setChecked(true);
		bankRadioButton.setChecked(false);
		checkRadioButton.setChecked(false);
		
		if (checkView.getVisibility() == View.VISIBLE)
		{
			checkView.setVisibility(View.GONE);
		} 
		else if (bankView.getVisibility() == View.VISIBLE)
		{
			bankView.setVisibility(View.GONE);
		}
		
		firstBankRadio = 2;
		creditView.setVisibility(View.VISIBLE);
		setBalanceCreditMoney();
	}
	
	private void setBankRadioClick()
	{
		bankRadioButton.setChecked(true);
		creditRadioButton.setChecked(false);
		checkRadioButton.setChecked(false);
		
		if (checkView.getVisibility() == View.VISIBLE)
		{
			checkView.setVisibility(View.GONE);
		} 
		else if (creditView.getVisibility() == View.VISIBLE)
		{
			creditView.setVisibility(View.GONE);
		}
		
		firstBankRadio = 3;
		bankView.setVisibility(View.VISIBLE);
		setBalanceBankMoney();
	}
	
	private void initClickListener()
	{
		checkRadioButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				setCheckRadioClick();
			}
		});
		
		creditRadioButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				setCreditRadioClick();
			}
		});
		
		bankRadioButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				setBankRadioClick();
			}
		});
		
		bankView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(CashDrawingActivity.this, RadioDialogActivity.class);
				intent.putExtra(RadioDialogActivity.RADIODATA, bankList);
				intent.putExtra(RadioDialogActivity.RADIOSELECT, bankTextView.getText().toString());
				startActivityForResult(intent, REQUEST_BANK);
			}
		});
		
		checkView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(CashDrawingActivity.this, RadioDialogActivity.class);
				intent.putExtra(RadioDialogActivity.RADIODATA, checkList);
				intent.putExtra(RadioDialogActivity.RADIOSELECT, checkTextView.getText().toString());
				startActivityForResult(intent, REQUEST_CHECK);
			}
		});
		
		creditView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(CashDrawingActivity.this, RadioDialogActivity.class);
				intent.putExtra(RadioDialogActivity.RADIODATA, creditList);
				intent.putExtra(RadioDialogActivity.RADIOSELECT, creditTextView.getText().toString());
				startActivityForResult(intent, REQUEST_CREDIT);
			}
		});
		
		dateView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
//				DatePickerDialog dpd = new DatePickerDialog(CashDrawingActivity.this, new OnDateSetListener()
//				{
//					@Override
//					public void onDateSet(DatePicker view, int year, int monthOfYear,
//							int dayOfMonth)
//					{
//						dateTextView.setText(BDUtil.getDate(year, (monthOfYear+1), dayOfMonth));
//						
//						toYear = year;
//						toMonth = monthOfYear;
//						toDay = dayOfMonth;
//					}
//				}, toYear, toMonth, toDay);
//				
//				dpd.show();
				
				CalendarPickerDialog cpd = new CalendarPickerDialog(superContext, new CalendarPickerDialog.ICalendarPickerDateSetListener() {
					@Override
					public void onDateSet(int year, int monthOfYear, int dayOfMonth) {
						
						dateTextView.setText(BDUtil.getDate(year, (monthOfYear+1), dayOfMonth));
						
						toYear = year;
						toMonth = monthOfYear;
						toDay = dayOfMonth;
					}
				}, toYear, toMonth, toDay);
				
				cpd.show();
			}
		});
		
		categoryView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(CashDrawingActivity.this, RadioDialogActivity.class);
				intent.putExtra(RadioDialogActivity.RADIODATA, categoryList);
				intent.putExtra(RadioDialogActivity.RADIOSELECT, categoryTextView.getText().toString());
				intent.putExtra(RadioDialogActivity.RADIOTYPE, RadioDialogActivity.CATEGORY_MOVE_TYPE);
				intent.putExtra(RadioDialogActivity.RADIOBUTTONSTRING, RadioDialogActivity.CATEGORY_MOVE_TYPE_STRING);
				startActivityForResult(intent, REQUEST_CATEGORY);
			}
		});
		
		insertButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (money.length() < 1)
				{
					BDUtil.showDialog(CashDrawingActivity.this, "금액오류", "금액을 정확히 입력해주세요.");
					return;
				}
				
				if (checkRadioButton.isChecked())
				{
					if ((Boolean) checkView.getTag() == false)
					{
						BDUtil.showDialogManager(superContext, "체크카드가 하나도 없습니다.");
						return;
					}
				} 
				else if (bankRadioButton.isChecked())
				{
					if ((Boolean) bankView.getTag() == false)
					{
						BDUtil.showDialogManager(superContext, "통장이 하나도 없습니다.");
						return;
					}
				} 
				else if (creditRadioButton.isChecked())
				{
					if ((Boolean) creditView.getTag() == false)
					{
						BDUtil.showDialogManager(superContext, "신용카드가 하나도 없습니다.");
						return;
					}
				}
				
				new ShowDialog().execute(BDUtil.asyncFlag);
			}
		});
	}
	
	private void insertOutData() throws Exception
	{
		String type = "";
		String moneyKind = "";
		
		if (charge.getText() != null && BDUtil.getCommaDel(charge.getText().toString()).length() != 0) 
		{
			chargeMoney = new BigDecimal(BDUtil.getCommaDel(charge.getText().toString()));
		} 
		else 
		{
			chargeMoney = BigDecimal.ZERO;
		}
		
		if (checkRadioButton.isChecked())
		{
			if (!checkOutInsert())
			{
				return;
			}
			
			type = BDConstents.CHECK_TYPE;
			moneyKind = checkTextView.getText().toString();
		} 
		else if (bankRadioButton.isChecked())
		{
			if (!bankOutInsert())
			{
				return;
			}
			
			type = BDConstents.BANK_TYPE;
			moneyKind = bankTextView.getText().toString();
		} 
		else if (creditRadioButton.isChecked())
		{
			if (!creditOutInsert())
			{
				return;
			}
			
			type = BDConstents.CREDIT_TYPE;
			moneyKind = creditTextView.getText().toString();
		}
		
		// 잔액을 입력 하기 전에 타입과 이름이 없으면 익셉션 발생
		if (type.equals("") || moneyKind.equals(""))
		{
			throw new Exception();
		}
		
		// 잔액을 입력한다.
		BalanceQuery balace = new BalanceQuery(superContext);
		balace.setBalance(type, moneyKind);
		
		// 카테고리 카운트 하나 증가
		sql.selectMapTile(this, "SELECT count FROM category_move_list WHERE kind = '" +
				BDUtil.getApostrophe(categoryTextView.getText().toString()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int countIndex = c.getColumnIndex("count");
				int count = 0;
				
				c.moveToFirst();
				for (int i = 0; i < c.getCount(); i++)
				{
					count = c.getInt(countIndex);
					c.moveToNext();
				}
				
				count++;
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("count", "" + count);
				String [] whereArgs = new String[]{categoryTextView.getText().toString()};
				sql.update(superContext, "category_move_list", map, "kind = ?", whereArgs);
			}
		});
	}

	private boolean checkOutInsert()
	{
		sql.selectMapTile(this, "SELECT banklink FROM check_card WHERE name = '" 
				+ BDUtil.getApostrophe(checkTextView.getText().toString()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				linkId = -1;
				int banklinkIndex = c.getColumnIndex("banklink");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					linkId = c.getInt(banklinkIndex);
					c.moveToNext();
				}
				
				if (linkId > -1)
				{
					sql.selectMapTile(CashDrawingActivity.this, "SELECT money FROM bankbook WHERE id = " + linkId, new ParseSelectData()
					{
						@Override
						public void resultData(Cursor c)
						{
//							int tempMoney = Integer.parseInt(money.getText().toString());
							BigDecimal tempMoney = new BigDecimal(BDUtil.getCommaDel(money.getText().toString()));
							
							int moneyIndex = c.getColumnIndex("money");
							
							c.moveToFirst();
							BigDecimal dbMoney = BigDecimal.ZERO;
							for (int i = 0; i < c.getCount(); i++)
							{
//								tempMoney = Integer.parseInt(c.getString(moneyIndex)) - tempMoney - chargeMoney;
								dbMoney = dbMoney.add(new BigDecimal(c.getString(moneyIndex)));
								c.moveToNext();
							}
							
							dbMoney = dbMoney.subtract(tempMoney);
							dbMoney = dbMoney.subtract(chargeMoney);
							
							HashMap<String, String> map = new HashMap<String, String>();
							map.put("money", dbMoney.toString());
							String [] whereArgs = new String[]{linkId + ""};
							sql.update(CashDrawingActivity.this, "bankbook", map, "id = ?", whereArgs);
							
							linkType = 2;
						}
					});
				}
				else
				{
					BDUtil.showDialog(CashDrawingActivity.this, "체크카드에러", "체크카드가 연결된 통장이 업습니다.");
				}
			}
		});
		
		moneyUpdate();

		setInOutTable(checkTextView.getText().toString(), linkType);
		
		return true;
	}
	
	private boolean creditOutInsert()
	{
		sql.selectMapTile(CashDrawingActivity.this, "SELECT id, outmoney FROM credit_card WHERE name = '" 
				+ BDUtil.getApostrophe(creditTextView.getText().toString()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
//				int tempMoney = Integer.parseInt(money.getText().toString());
				BigDecimal tempMoney = new BigDecimal(BDUtil.getCommaDel(money.getText().toString()));
				int id = -1;
				
				int idIndex = c.getColumnIndex("id");
				int moneyIndex = c.getColumnIndex("outmoney");
				
				c.moveToFirst();
				BigDecimal dbMoney = BigDecimal.ZERO;
				for (int i = 0; i < c.getCount(); i++)
				{
					id = c.getInt(idIndex);
//					tempMoney = Integer.parseInt(c.getString(moneyIndex)) + tempMoney + chargeMoney;
					dbMoney = dbMoney.add(new BigDecimal(c.getString(moneyIndex)));
					c.moveToNext();
				}
				
				dbMoney = dbMoney.add(tempMoney);
				dbMoney = dbMoney.add(chargeMoney);
				
				if (id > -1)
				{
					HashMap<String, String> map = new HashMap<String, String>();
					map.put("outmoney", dbMoney.toString());
					String [] whereArgs = new String[]{id + ""};
					sql.update(CashDrawingActivity.this, "credit_card", map, "id = ?", whereArgs);
				}
				
				linkType = 3;
			}
		});
		
		moneyUpdate();
		
		setInOutTable(creditTextView.getText().toString(), linkType);
		
		return true;
	}
	
	private boolean bankOutInsert()
	{
		sql.selectMapTile(CashDrawingActivity.this, 
				"SELECT id, money FROM bankbook WHERE name = '" 
				+ BDUtil.getApostrophe(bankTextView.getText().toString()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
//				int tempMoney = Integer.parseInt(money.getText().toString());
				BigDecimal tempMoney = new BigDecimal(BDUtil.getCommaDel(money.getText().toString()));
				int id = -1;
				
				int idIndex = c.getColumnIndex("id");
				int moneyIndex = c.getColumnIndex("money");
				
				c.moveToFirst();
				BigDecimal dbMoney = BigDecimal.ZERO;
				for (int i = 0; i < c.getCount(); i++)
				{
					id = c.getInt(idIndex);
//					tempMoney = Integer.parseInt(c.getString(moneyIndex)) - tempMoney - chargeMoney;
					dbMoney = dbMoney.add(new BigDecimal(c.getString(moneyIndex)));
					c.moveToNext();
				}
				
				dbMoney = dbMoney.subtract(tempMoney);
				dbMoney = dbMoney.subtract(chargeMoney);
				
				if (id > -1)
				{
					HashMap<String, String> map = new HashMap<String, String>();
					map.put("money", dbMoney.toString());
					String [] whereArgs = new String[]{id + ""};
					sql.update(CashDrawingActivity.this, "bankbook", map, "id = ?", whereArgs);
				}
				
				linkType = 1;
			}
		});
		
		moneyUpdate();
		
		setInOutTable(bankTextView.getText().toString(), linkType);
		
		return true;
	}
	
	private void moneyUpdate() 
	{
		// 신용카드가 아닐 경우에만 통장 갱신
		if (!creditRadioButton.isChecked())
		{
			sql.selectMapTile(this, "SELECT money FROM bank_money", new ParseSelectData()
			{
				@Override
				public void resultData(Cursor c)
				{
//					int tempMoney = Integer.parseInt(money.getText().toString());
					BigDecimal tempMoney = new BigDecimal(BDUtil.getCommaDel(money.getText().toString()));
					int moneyIndex = c.getColumnIndex("money");
					
					c.moveToFirst();
					BigDecimal dbMoney = BigDecimal.ZERO;
					for (int i = 0; i < c.getCount(); i++)
					{
//						tempMoney = Integer.parseInt(c.getString(moneyIndex)) - tempMoney - chargeMoney;
						dbMoney = dbMoney.add(new BigDecimal(c.getString(moneyIndex)));
						c.moveToNext();
					}
					
					dbMoney = dbMoney.subtract(tempMoney);
					dbMoney = dbMoney.subtract(chargeMoney);
					
					HashMap<String, String> map = new HashMap<String, String>();
					map.put("money", dbMoney.toString());
					sql.update(CashDrawingActivity.this, "bank_money", map, null, null);
				}
			});
		}
		
		sql.selectMapTile(this, "SELECT money FROM total_money", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
//				int tempMoney = Integer.parseInt(money.getText().toString());
				BigDecimal tempMoney = new BigDecimal(BDUtil.getCommaDel(money.getText().toString()));
				int moneyIndex = c.getColumnIndex("money");
				
				c.moveToFirst();
				BigDecimal dbMoney = BigDecimal.ZERO;
				for (int i = 0; i < c.getCount(); i++)
				{
					dbMoney = dbMoney.add(new BigDecimal(c.getString(moneyIndex)));
					
//					if (creditRadioButton.isChecked())
//					{
//						tempMoney = Integer.parseInt(c.getString(moneyIndex)) + tempMoney;
//					}
//					else
//					{
//						tempMoney = Integer.parseInt(c.getString(moneyIndex)) - chargeMoney;
//					}
					c.moveToNext();
				}
				
				if (creditRadioButton.isChecked())
				{
					dbMoney = dbMoney.add(tempMoney);
				}
				else
				{
					dbMoney = dbMoney.subtract(chargeMoney);
				}
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("money", dbMoney.toString());
				sql.update(CashDrawingActivity.this, "total_money", map, null, null);
			}
		});
		
		sql.selectMapTile(this, "SELECT money FROM real_money", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
//				int tempMoney = Integer.parseInt(money.getText().toString());
				BigDecimal tempMoney = new BigDecimal(BDUtil.getCommaDel(money.getText().toString()));
				int moneyIndex = c.getColumnIndex("money");
				
				c.moveToFirst();
				BigDecimal dbMoney = BigDecimal.ZERO;
				for (int i = 0; i < c.getCount(); i++)
				{
//					tempMoney = Integer.parseInt(c.getString(moneyIndex)) + tempMoney;
					dbMoney = dbMoney.add(new BigDecimal(c.getString(moneyIndex)));
					c.moveToNext();
				}
				
				dbMoney = dbMoney.add(tempMoney);
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("money", dbMoney.toString());
				sql.update(CashDrawingActivity.this, "real_money", map, null, null);
			}
		});
	}
	
	
	private void setInOutTable(String moneyKind, int linkType)
	{
		
		HashMap<String, String> map = new HashMap<String, String>();
		
		if (linkType == 1 || linkType == 2)
		{
			map.put("inmoney", BDUtil.getCommaDel(money.getText().toString()));
			map.put("outmoney", BDUtil.getCommaDel(money.getText().toString()));
//			map.put("category", BDConstents.CATEGORY_MONEY_INOUT);
			map.put("category", categoryTextView.getText().toString());
		}
		else if (linkType == 3)
		{
			map.put("inmoney", BDUtil.getCommaDel(money.getText().toString()));
			map.put("postmoney", BDUtil.getCommaDel(money.getText().toString()));
//			map.put("category", BDConstents.CATEGORY_MONEY_SERVICE);
			map.put("category", categoryTextView.getText().toString());
		}
		
		String date = dateTextView.getText().toString();
		date = date.replace(" ", "");
		date = date.replace("-", "");
		map.put("date", date);
		map.put("type", "4");
		map.put("moneykind", moneyKind);
		map.put("linkid", -1+"");
		map.put("linktype", linkType+"");
		
		map.put("memo", memo.getText().toString());
		
		sql.insert(this, map, "in_out");
		
		if ( chargeMoney.compareTo(BigDecimal.ZERO) == 1) 
		{
			sql.selectMapTile(this, "SELECT max(id) maxid FROM in_out;", new ParseSelectData()
			{
				@Override
				public void resultData(Cursor c)
				{
					int idIndex = c.getColumnIndex("maxid");
					
					c.moveToFirst();
					
					for (int i = 0; i < c.getCount(); i++)
					{
						inoutLinkId = c.getInt(idIndex);
						c.moveToNext();
					}
				}
			});
			map.clear();
			
			if (linkType == 1 || linkType == 2)
			{
				map.put("outmoney", chargeMoney+"");
			}
			else if (linkType == 3)
			{
				map.put("postmoney", chargeMoney+"");
			}
			
			map.put("date", date);
			map.put("type", "4");
			map.put("moneykind", moneyKind);
			map.put("category", BDConstents.CATEGORY_SUSUMONEY);
//			map.put("linkid", inoutLinkId+"");
			map.put("linktype", linkType+"");
			sql.insert(this, map, "in_out");

			map.clear();
			map.put("linkid", (inoutLinkId+1)+"");
			String [] whereArgs = new String[]{inoutLinkId + ""};
			sql.update(CashDrawingActivity.this, "in_out", map, "id = ?", whereArgs);
		}
	}
	
	private void setBalanceCheckMoney()
	{
		sql.selectMapTile(this, "SELECT banklink FROM check_card WHERE name = '"
				+ BDUtil.getApostrophe(checkTextView.getText().toString()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int count = c.getCount();
				
				int columIndex = c.getColumnIndex("banklink");
				c.moveToFirst();
				int banklink = 0;
				for (int i = 0; i < count; i++)
				{
					banklink = c.getInt(columIndex);
					c.moveToNext();
				}
				
				sql.selectMapTile(CashDrawingActivity.this, "SELECT money FROM bankbook WHERE id = " + banklink, new ParseSelectData()
				{
					@Override
					public void resultData(Cursor c)
					{
						int count = c.getCount();
						
						int columIndex = c.getColumnIndex("money");
						c.moveToFirst();
//						int money = 0;
						BigDecimal money = BigDecimal.ZERO;
						for (int i = 0; i < count; i++)
						{
//							money = money + Integer.parseInt(c.getString(columIndex));
							money = money.add(new BigDecimal(c.getString(columIndex)));									
							c.moveToNext();
						}
						
						balanceText.setText("체크잔액");
						balanceMoney.setText(BDUtil.getWon(money.toString()) + shape);
					}
				});
			}
		});
	}
	
	private void setBalanceCreditMoney()
	{
		sql.selectMapTile(this, "SELECT outmoney FROM credit_card WHERE name = '"
				+ BDUtil.getApostrophe(creditTextView.getText().toString()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int count = c.getCount();
				
				int columIndex = c.getColumnIndex("outmoney");
				c.moveToFirst();
//				int money = 0;
				BigDecimal money = BigDecimal.ZERO;
				for (int i = 0; i < count; i++)
				{
//					money = money + Integer.parseInt(c.getString(columIndex));
					money = money.add(new BigDecimal(c.getString(columIndex)));
					c.moveToNext();
				}
				
				balanceText.setText("카드대금");
				balanceMoney.setText(BDUtil.getWon(money.toString()) + shape);
			}
		});
	}
	
	private void setBalanceBankMoney()
	{
		sql.selectMapTile(CashDrawingActivity.this, 
				"SELECT money FROM bankbook WHERE name = '" 
				+ BDUtil.getApostrophe(bankTextView.getText().toString()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int count = c.getCount();
				
				int columIndex = c.getColumnIndex("money");
				c.moveToFirst();
//				int money = 0;
				BigDecimal money = BigDecimal.ZERO;
				for (int i = 0; i < count; i++)
				{
//					money = money + Integer.parseInt(c.getString(columIndex));
					money = money.add(new BigDecimal(c.getString(columIndex)));
					c.moveToNext();
				}
				
				balanceText.setText("통장잔액");
				balanceMoney.setText(BDUtil.getWon(money.toString()) + shape);
			}
		});
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		
		if (requestCode == REQUEST_BANK)
		{
			if (resultCode == Activity.RESULT_OK)
			{
				String selectData = data.getStringExtra(RadioDialogActivity.RADIOSTRING);
				bankTextView.setText(selectData);
				
				if (firstBankRadio == 3)
				{
					setBalanceBankMoney();
				}
			}
		}
		else if (requestCode == REQUEST_CHECK)
		{
			if (resultCode == Activity.RESULT_OK)
			{
				String selectData = data.getStringExtra(RadioDialogActivity.RADIOSTRING);
				checkTextView.setText(selectData);
				
				if (firstBankRadio == 1)
				{
					setBalanceCheckMoney();
				}
			}
		}
		else if (requestCode == REQUEST_CREDIT)
		{
			if (resultCode == Activity.RESULT_OK)
			{
				String selectData = data.getStringExtra(RadioDialogActivity.RADIOSTRING);
				creditTextView.setText(selectData);
				
				if (firstBankRadio == 2)
				{
					setBalanceCreditMoney();
				}
			}
		}
		else if (requestCode == REQUEST_CATEGORY)
		{
			if (resultCode == Activity.RESULT_OK)
			{
				String selectData = data.getStringExtra(RadioDialogActivity.RADIOSTRING);
				categoryTextView.setText(selectData);
			}
			else if (resultCode == RadioDialogActivity.REFRESH_CATEGORY)
			{
				final String beforeCategory = categoryTextView.getText().toString();
				
				sql.selectMapTile(this, "SELECT kind FROM category_move_list ORDER BY count DESC", new ParseSelectData()
				{
					@Override
					public void resultData(Cursor c)
					{
						categoryList = new ArrayList<String>();
						
						int nameIndex = c.getColumnIndex("kind");
						c.moveToFirst();
						
						for (int i = 0; i < c.getCount(); i++)
						{
							String kind = c.getString(nameIndex);
							categoryList.add(kind);
							c.moveToNext();
						}
						
						if (categoryList.size() < 1)
						{
							String memo = "없음";
							categoryList.add(memo);
							categoryView.setClickable(false);
						}
						
						categoryTextView.setText(beforeCategory);
					}
				});
			}
		}
	}
	
	/**
	 * 다이얼로그 뛰우기 
	 */
	private class ShowDialog extends AsyncTask<Integer, Integer, Integer>{
		ProgressDialog dialog = null;
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			
			if (BDUtil.btnEnable)
			{
				BDUtil.btnEnable = false;
				BDUtil.asyncFlag = -1;
				
				dialog = new ProgressDialog(CashDrawingActivity.this);
				dialog.setCancelable(false);
				dialog.setMessage("Loading...");
				dialog.show();
			}
		}
		
		@Override
		protected Integer doInBackground(Integer... arg0) {
			if (arg0[0] == 0) 
			{
				try
				{
					sql.beginTansaction(superContext);
					
					insertOutData();
					
					sql.setTransactionSuccessful();
				} catch (Exception e)
				{
					return -1;
				} finally {
					try 
					{
						sql.endTransaction(superContext);
					} catch (Exception e) {
						return -1;
					}
				}
			}
			else
			{
				return arg0[0];
			}
			
			return arg0[0];
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			
			if (dialog != null) {
				dialog.dismiss();
			}
			
			if (result == -1)
			{
				BDUtil.btnEnable = true;
				BDUtil.asyncFlag = 0;
				
				BDUtil.showDialog(superContext, "오류", "데이터 저장에 실패했습니다.");
			}
			else if (result == 0) 
			{
				BDUtil.showDialogFinish(CashDrawingActivity.this, "알림", "현금출금이 처리 되었습니다.");
			}
		}
	}

	@Override
	protected void tipButton()
	{
	}
}
